angular.module('todoApp').controller('todoController', ['$scope', 'todoService', function($scope, todoService) {
  const { todoList, archivedList } = todoService.query();

  $scope.todoList = todoList;
  $scope.archivedList = archivedList;

  $scope.$watch('todoList', function() {
    todoService.save({
      todoList: $scope.todoList,
      archivedList: $scope.archivedList
    });
  }, true);

  $scope.addItem = function(content) {
    $scope.todoList.push({
      content,
      checked: false,
      archived: false,
      time: new Date().toLocaleString()
    });
  };
  $scope.onChangeOrder = function(ascend) {
    $scope.todoList = $scope.todoList.sort((a, b) => {
      if (a.time === b.time) return 0;
      if (ascend) {
        return a.time < b.time ? 1 : -1;
      } else {
        return a.time > b.time ? 1 : -1;
      }
    });
  };

  $scope.dialogVisible = false;
  $scope.archiveItem = {};
  $scope.undo = function(item) {
    const target = $scope.todoList.find(x => x === item);
    if (target) {
      target.checked = false;
    }
  };
  $scope.archive = function(item) {
    console.log('archive');
    $scope.archiveItem = item;
    $scope.dialogVisible = true;
  };
  $scope.archiveAll = function() {
    console.log('archiveAll');
    $scope.archiveItem = {};
    $scope.dialogVisible = true;
  };
  $scope.confirmArchive = function() {
    console.log($scope.archiveItem);
    if (Object.keys($scope.archiveItem).length === 0) {
      $scope.archivedList.push(...angular.copy($scope.todoList.filter(item => item.checked)));
      $scope.todoList = $scope.todoList.filter(item => !item.checked);
    } else {
      const index = $scope.todoList.findIndex(x => x === $scope.archiveItem);
      if (index !== -1) {
        $scope.archivedList.push(angular.copy($scope.archiveItem));
        $scope.todoList.splice(index, 1);
      }
    }
    $scope.dialogVisible = false;
  };
  $scope.cancelArchive = function () {
    $scope.dialogVisible = false;
  };
}]);